package com.everflourish.yeah100.act.markingsystem;

import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.everflourish.yeah100.R;
import com.everflourish.yeah100.act.base.BaseFragment;
import com.everflourish.yeah100.adapter.FragmentStandardAdapter;
import com.everflourish.yeah100.entity.marking.Standard;
import com.everflourish.yeah100.entity.marking.StandardAnswer;
import com.everflourish.yeah100.entity.marking.Topic;
import com.everflourish.yeah100.http.MarkingSystemRequest;
import com.everflourish.yeah100.ui.dialog.SingleAnswerDialog;
import com.everflourish.yeah100.utils.AnswerUtil;
import com.everflourish.yeah100.utils.JsonUtil;
import com.everflourish.yeah100.utils.LogUtil;
import com.everflourish.yeah100.utils.MyToast;
import com.everflourish.yeah100.utils.TopicUtil;
import com.everflourish.yeah100.utils.collections.TopicCollections;
import com.everflourish.yeah100.utils.constant.Constant;
import com.everflourish.yeah100.utils.constant.PaperType;
import com.everflourish.yeah100.utils.constant.ResultCode;
import com.pnikosis.materialishprogress.ProgressWheel;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * 作者：Created by liqisi on 2016/6/3.
 * 时间：2016/6/3
 */
public class FragmentStandardAnswer extends BaseFragment implements View.OnClickListener {

    private List<StandardAnswer> mList;
    private FragmentStandardAdapter mAdapter;
    private GridView mExamStandardGv;
    private MarkingMenuActivity mMarkingMenuActivity;
    private MarkingSystemRequest mRequest;
    private LinearLayout mStandardContentLl;
    private FrameLayout mRefreshFl;
    private ProgressWheel mProgress;
    private TextView mUploadTv, mRefreshTv;
    public Button mReadCardBt;
    public List<Topic> mTopics;
    public List<Standard> mStandards;
    private List<Standard> uploadStandards;
    public boolean isUpdate = false;
    // 是否刷新：当基础信息，题型修改后isRefresh = true;
    private boolean isRefresh = false;
    private Context mContext;
    private boolean isPrepared;  //  标志位，标志已经初始化完成。
    public boolean isFirstRefresh = true;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_standard_answer, container,
                false);
        isPrepared = true;
        return view;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initData();
        initWidget();
        lazyLoad();
    }

    /**
     * tab懒加载（当显示页面时才刷新）
     */
    @Override
    protected void lazyLoad() {
        if (!isPrepared || !isVisible) {
            return;
        }
        getStandardRequest();
        isPrepared = false;
    }

    private void initData() {
        mList = new ArrayList<StandardAnswer>();
        mContext = mMarkingMenuActivity = (MarkingMenuActivity) getActivity();
        mRequest = MarkingSystemRequest.getInstance();
        mAdapter = new FragmentStandardAdapter(mContext, mList);
    }

    private void initWidget() {
        mStandardContentLl = (LinearLayout) getView().findViewById(R.id.stadard_content_ll);
        mExamStandardGv = (GridView) getView().findViewById(R.id.standard_answer_gl);
        mExamStandardGv.setAdapter(mAdapter);
        mExamStandardGv.setOnItemClickListener(itemClickListener);
        mProgress = (ProgressWheel) getView().findViewById(R.id.standard_progress);
        mUploadTv = (TextView) getView().findViewById(R.id.standard_upload_sure);
        mUploadTv.setOnClickListener(this);
        mReadCardBt = (Button) getView().findViewById(R.id.standard_read_bt);
        mReadCardBt.setOnClickListener(this);
        mRefreshFl = (FrameLayout) getView().findViewById(R.id.topic_refresh_fl);
        mRefreshTv = (TextView) getView().findViewById(R.id.include_refresh_tv);
        mRefreshTv.setTextColor(mContext.getResources().getColor(R.color.marking_appbar_primaryDark));
        mRefreshTv.setOnClickListener(this);
    }

    /**
     * 刷新数据
     */
    public void refreshData() {
        isRefresh = true;
        mTopics = null;
        if (isVisible()) {
            getStandardRequest();
        }
        isFirstRefresh = true;
    }

    AdapterView.OnItemClickListener itemClickListener = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                                int position, long id) {
            showAlterDialog(position);
        }
    };

    /**
     * 获取标准答案请求
     */
    public void getStandardRequest() {
        isRefresh = false;
        mProgress.setVisibility(View.VISIBLE);
        JsonObjectRequest request = mRequest.getAggregateRequest(
                mMarkingMenuActivity.mExamination.getId(), true, true, false,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        getStandardExaminationListener(response);
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        mRequest.disposeError(mContext, mLoadDialog, error, "获取标准答案失败");
                        mProgress.setVisibility(View.GONE);
                        mStandardContentLl.setVisibility(View.GONE);
                        mRefreshFl.setVisibility(View.VISIBLE);
                    }
                });
        mQueue.add(request);
//        mQueue.start();
    }

    /**
     * 上传标准答案请求
     *
     * @param standards
     */
    public void uploadStandardRequest(List<Standard> standards) {
        mProgress.setVisibility(View.VISIBLE);
        JsonObjectRequest request = mRequest.uploadStandardRequest(
                mMarkingMenuActivity.mExamination.getId(),
                mMarkingMenuActivity.mExamination.getLastModifiedTime(), standards,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        uploadStandardExaminationListener(response);
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        mProgress.setVisibility(View.GONE);
                        mRequest.disposeError(mContext, mLoadDialog, error, "保存标准答案失败");
                    }
                });
        mQueue.add(request);
//        mQueue.start();
    }

    /**
     * 获取标准答案监听
     *
     * @param response
     */
    private void getStandardExaminationListener(JSONObject response) {
        String resultCode = "";
        try {
            resultCode = response.getString(Constant.RESULT_CODE);
            if (resultCode.equals(ResultCode.result_ok.resultCode)) {
                // 获取题型
                mTopics = AnswerUtil.getTopics(response);
                // 获取标准答案
                mStandards = AnswerUtil.getStandardAnswers(response);
                String lastModifiedTime = JsonUtil.getLastModifiedTime(
                        response, null);
                mMarkingMenuActivity.mExamination
                        .setLastModifiedTime(lastModifiedTime);
                setListData(mStandards);
//                mStandardContentLl.setVisibility(View.VISIBLE);
                mExamStandardGv.setVisibility(View.VISIBLE);
//                setButtonStatus(false);
            } else if (resultCode
                    .equals(ResultCode.result_000001E.resultCode)) {
                MyToast.showShort(mContext, R.string.readcard_07061_000001E);
            } else if (resultCode
                    .equals(ResultCode.result_000012E.resultCode)) {
                MyToast.showShort(mContext, R.string.readcard_07062_000012E);
            } else if (resultCode
                    .equals(ResultCode.result_300001E.resultCode)) {
                MyToast.showShort(mContext, R.string.readcard_07063_300001E);
            } else if (resultCode
                    .equals(ResultCode.result_system_exception_999999E)) {
                MyToast.showShort(mContext, R.string.readcard_070699_999999E);
            } else {
                MyToast.showShort(mContext, "获取标准答案失败");
            }
        } catch (JSONException e) {
            e.printStackTrace();
            LogUtil.e("JSON异常", e);
            MyToast.showShort(mContext, "获取标准答案失败");
        } finally {
            mProgress.setVisibility(View.GONE);
        }
    }

    /**
     * 保存标准答案监听
     *
     * @param response
     */
    private void uploadStandardExaminationListener(JSONObject response) {
        try {
            String resultCode = response.getString(Constant.RESULT_CODE);
            if (resultCode.equals(ResultCode.result_ok.resultCode)
                    || resultCode
                    .equals(ResultCode.result_300018W.resultCode)) {
                mStandards = uploadStandards;
                mMarkingMenuActivity.isUpdateExamination = true;
                String lastModifiedTime = JsonUtil.getLastModifiedTime(
                        response, null);
                mMarkingMenuActivity.mExamination
                        .setLastModifiedTime(lastModifiedTime);
                // 提交标准答案后，弹出对话框，提示是否要进行下一步操作：阅卷，读学生成绩
//                PromptDialog promptDialog = new PromptDialog(mContext,
//                        "提示", "已成功保存标准答案，是否要进行下一步智能阅卷！");
                if (mMarkingMenuActivity.mFragmentReadPaper.mRefreshListener != null) {
                    mMarkingMenuActivity.mFragmentReadPaper.mRefreshListener.onRefresh();
                }
                MyToast.showShort(mContext, "上传标准答案成功");
            } else if (resultCode
                    .equals(ResultCode.result_000001E.resultCode)) {
                MyToast.showShort(mContext, R.string.readcard_07051_000001E);
            } else if (resultCode
                    .equals(ResultCode.result_000012E.resultCode)) {
                MyToast.showShort(mContext, R.string.readcard_07052_000012E);
            } else if (resultCode
                    .equals(ResultCode.result_300001E.resultCode)) {
                MyToast.showShort(mContext, R.string.readcard_07053_300001E);
            } else if (resultCode
                    .equals(ResultCode.result_300018W.resultCode)) {
                MyToast.showShort(mContext, R.string.readcard_07054_300018W);
            } else if (resultCode
                    .equals(ResultCode.result_300019E.resultCode)) {
                String errorMsg = response.getString("errorMessage");
                MyToast.showShort(mContext, errorMsg);
            } else if (resultCode
                    .equals(ResultCode.result_version_unlike_exception_777777E.resultCode)) {
                MyToast.showShort(mContext, "当前数据已被更改，请刷新后操作");
            } else if (resultCode
                    .equals(ResultCode.result_system_exception_999999E)) {
                MyToast.showShort(mContext, R.string.readcard_070599_999999E);
            } else {
                MyToast.showShort(mContext, "保存标准答案失败");
            }
        } catch (JSONException e) {
            LogUtil.e("JSON异常", e);
            MyToast.showShort(mContext, "保存标准答案失败");
        } finally {
            mProgress.setVisibility(View.GONE);
            isUpdate = false;
        }
    }

    /**
     * List<Standard>转List<StandardAnswer>
     *
     * @param standards
     */
    private void setListData(List<Standard> standards) {
        Collections.sort(mTopics, new TopicCollections(false));
        if (standards == null) {
            return;
        }
        List<StandardAnswer> answerList = null;
        if (mStandards != null && mStandards.size() > 0) {
            // TODO
            answerList = AnswerUtil.answerToList(mStandards.get(0)
                    .getContent(), mTopics);
        } else {
            answerList = AnswerUtil.answerToList(null, mTopics);
        }
        mList.clear();
        mList.addAll(answerList);
        mAdapter.notifyDataSetChanged();
    }

    /**
     * 显示修改对话框
     *
     * @param position
     */
    private void showAlterDialog(final int position) {
        List<String> items = new ArrayList<String>();
        items.add("A");
        items.add("B");
        items.add("C");
        items.add("D");
        items.add("E");
        items.add("F");
        items.add("G");
        items.add("H");

        // 当点击了item后，弹出修改对话框
        boolean isSingle = true;
        int serialNumber = mList.get(position).getSerialNumber();
        final String answer = mList.get(position).getAnswer();
        int type = AnswerUtil.getCurrentTopicType(serialNumber, mTopics);
        String title = null;
        if (type == 1) {// 单选
            isSingle = true;
            title = "第" + serialNumber + "题(单选)： " + answer;
        } else if (type == 2) {// 多选
            isSingle = false;
            title = "第" + serialNumber + "题(多选)：" + answer;
        }
        final SingleAnswerDialog answerDialog = new SingleAnswerDialog(
                mContext, title, null, isSingle, false);
        answerDialog.setIsCancelShrinkFlag(true);
        answerDialog.setItems(items, answer,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // 单选题
                        setPositionAnswer(position, answerDialog, answer);
                        if (position < mList.size() - 1) {
                            showAlterDialog(position + 1);
                            dialog.dismiss();
                        } else {
                            dialog.dismiss();
                        }
                    }
                });

        String confirmButtonText = "下一题";
        if (position == mList.size() - 1) {
            confirmButtonText = "完成";
        }
        answerDialog.setOnConfirmButton(confirmButtonText,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        setPositionAnswer(position, answerDialog, answer);
                        dialog.dismiss();
                        if (position < mList.size() - 1) {
                            showAlterDialog(position + 1);
                        }
                    }
                });
        String cancelButtonText = "上一题";
        if (position == 0) {
            cancelButtonText = "完成";
        }
        answerDialog.setOnCancelButton(cancelButtonText,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        setPositionAnswer(position, answerDialog, answer);
                        dialog.dismiss();
                        if (position > 0) {
                            showAlterDialog(position - 1);
                        }
                    }

                });
        answerDialog.show();
    }

    /**
     * 设置item答案
     *
     * @param position
     * @param answerDialog
     * @param answer
     */
    private void setPositionAnswer(final int position,
                                   final SingleAnswerDialog answerDialog, String answer) {
        String currentAnswer = answerDialog.getAnswer();
        if (!currentAnswer.equals(answer)) {
            mList.get(position).setAnswer(currentAnswer);
            mAdapter.notifyDataSetChanged();
            isUpdate = true;
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.standard_upload_sure:
                if (mRefreshFl.getVisibility() == View.VISIBLE) {
                    MyToast.showShort(mContext, "请先刷新");
                    return;
                }
                if (!isUpdate) {
                    MyToast.showLong(mContext, "答案没有修改");
                    return;
                }
                uploadStandards = new ArrayList<Standard>();
                String content = AnswerUtil.listToAnswer(mList,
                        TopicUtil.getCurrentMaxNo(mTopics));
                Standard standard = new Standard();
                standard.setContent(content);
                standard.setType("N");
                uploadStandards.add(standard);
                if (checkeAnswers(PaperType.NONE, mList)) {
                    return;
                }
                uploadStandardRequest(uploadStandards);
                break;
            case R.id.standard_read_bt:
                if (mRefreshFl.getVisibility() == View.VISIBLE) {
                    MyToast.showShort(mContext, "请先刷新");
                    return;
                }
                if (mMarkingMenuActivity.mBluetoothHelper.isConn) {
                    // 等待读卡
                    mMarkingMenuActivity.readStandardAnswer(mReadCardBt);
                } else {
                    mMarkingMenuActivity.openBluetooth();
                }
                break;
            case R.id.include_refresh_tv:
                mProgress.setVisibility(View.VISIBLE);
                mRefreshFl.setVisibility(View.GONE);
                mStandardContentLl.setVisibility(View.VISIBLE);
//                if (mMarkingMenuActivity.mExamination == null) {
//                MyToast.showShort(mContext, "请先创建或获取考试信息");
//                } else {
                getStandardRequest();
//                }
                break;
            default:
                break;
        }
    }

    /**
     * 检查答案
     *
     * @param paperType
     * @param standardAnswers
     * @return
     */
    public boolean checkeAnswers(PaperType paperType, List<StandardAnswer> standardAnswers) {
        for (StandardAnswer standardAnswer : standardAnswers) {
            String answer = standardAnswer.getAnswer();
            Integer serialNumber = standardAnswer.getSerialNumber();
            if (TextUtils.isEmpty(answer)) {
                StringBuffer sb = new StringBuffer();
                if (paperType == PaperType.A) {
                    sb.append("A卷：");
                } else if (paperType == PaperType.B) {
                    sb.append("B卷：");
                }
                sb.append("第" + serialNumber + "题不能为空!");
                MyToast.showLong(mContext, sb.toString());
                return true;
            }
        }
        return false;
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mQueue.stop();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        LogUtil.d("hidden：" + hidden);
        if (!hidden && isRefresh) {
            getStandardRequest();
        }
        if (mReadCardBt == null) {
            return;
        }
        if (hidden) {
            mMarkingMenuActivity.mReadFlag = mMarkingMenuActivity.NOT_READ_FLAG;
            mReadCardBt.setText("读卡");
        }
        super.onHiddenChanged(hidden);
    }

    /**
     * 设置断开的状态
     */
    public void setDisconnectStatus() {
        if (mMarkingMenuActivity.mReadFlag == mMarkingMenuActivity.STANDARD_FLAG) {
            mMarkingMenuActivity.mReadFlag = mMarkingMenuActivity.NOT_READ_FLAG;
        }
        mReadCardBt.setText("读卡");
    }

    /**
     * 完成读卡
     */
    public void readComplete(Map<String, Object> map) {
        // mEMenuActivity.mReadFlag = EMenuActivity.NOT_READ_FLAG;
        if (map == null) {
            mMarkingMenuActivity.sendCommandForBackward();
            MyToast.showLong(mContext, "读取答题卡失败!");
            return;
        }
        ArrayList<StandardAnswer> answerList = AnswerUtil.mapToStandardList(map,
                mTopics);
        mList.clear();
        mList.addAll(answerList);
        mAdapter.notifyDataSetChanged();
        isUpdate = true;
        // 判断是否全部已经填涂上。
        if (checkeAnswers(PaperType.NONE, answerList)) {
            mMarkingMenuActivity.sendCommandForBackward();
        } else {
            MyToast.showLong(mContext, "导入标准成绩成功");
            mMarkingMenuActivity.sendCommandForForward();
        }
    }
}